package com.xpgk.xpsoft.system;

import java.util.Date;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xpgk.common.kit.CacheKitEx;
import com.xpgk.common.kit.PubKit;
import com.xpgk.xpsoft.common.XPSoftService;
import com.xpgk.xpsoft.constants.XPSoftConstant;

//系统及系统参数
public class SystemService extends XPSoftService {
	static Record m_system;

	static public synchronized String saveParam(Record param) {
		Integer value = param.getInt("systemID");
		if (value == null)
			param.set("systemID", XPSoftConstant.systemID);

		param.remove("id");
		if (ExistParamType(param.getInt("systemID"), param.getStr("type")) != null) {
			return "type had exist";
		}
		;
		Db.save("FRM_SYSTEM_PARAM", param);
		return "ok";
	}

	// 添加用户
	static public Integer ExistParamType(Integer systemID, String type) {
		Record record = GetParam(type);
		if (record == null)
			return null;
		if (systemID != null && systemID.equals(record.getInt("systemID")))
			return record.getInt("id");
		else
			return Db.queryInt("select ID from FRM_SYSTEM_PARAM where SYSTEMID=? and TYPE=?", systemID, type);
	}

	static public String updateParam(Record param) {
		if (param == null || param.get("id") == null)
			return "错误信息。";
		Integer id = ExistParamType(param.getInt("systemID"), param.getStr("type"));
		if (id != null && id != PubKit.toInt(param.get("id"))) {
			return "type had exist";
		}
		;
		if (Db.update("FRM_SYSTEM_PARAM", param)) {
			CacheKitEx.remove(XPSoftConstant.cacheName,
					XPSoftConstant.cacheKey_param(param.getInt("systemID"), param.getStr("type")));
			return "ok";
		}
		return "错误信息。";
	}

	// 得到系统参数
	static public Record GetParam(String type) {
		Record record = CacheKitEx.get(XPSoftConstant.cacheName,
				XPSoftConstant.cacheKey_param(XPSoftConstant.systemID, type));
		if (record == null) {
			record = Db.findFirst("select * from FRM_SYSTEM_PARAM where SYSTEMID=? and TYPE=?", XPSoftConstant.systemID,
					type);
			CacheKitEx.put(XPSoftConstant.cacheName, XPSoftConstant.cacheKey_param(XPSoftConstant.systemID, type),
					record);
		}
		return record;
	}

	static public Record GetSystem() {
		if (m_system == null) {
			m_system = Db.findFirst("select * from FRM_SYSTEM where ID=?", XPSoftConstant.systemID);
		}
		return m_system;
	}

	static public String updateSystem(Record system) {
		if (system == null)
			return "错误信息。";
		Integer id = PubKit.toInt(system.get("id"));
		if (id == null) {
			system.set("CREATETIME", new Date());
			Db.save("FRM_SYSTEM", system);
			return "ok";
		} else {
			if (Db.update("FRM_SYSTEM", system)) {
				m_system = null;
				return "ok";
			}
		}
		return "错误信息。";
	}
}
